//
//  MainTabBar.swift
//  新浪微博-初建项目
//
//  Created by danny on 15/6/24.
//  Copyright © 2015年 DannyLiu. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {


    // 当系统布局不能满足要求的时候,用layoutSubviews来调整布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        // 设置子控件的布局
        
        // 目的是确定每个按钮起始的宽度的位置,因为系统自带的是UITabbarButton,而且是私有接口,不让用.我们要进行判断是UIControl而且非我们要添加的UIButton,就可以区分自带按钮和我们添加的按钮,并进行布局
        
        // 先确定每个的宽和高
        let w = self.bounds.width / 5
        
        let rect = CGRectMake(0, 0, w, bounds.height)
        
        var index = 0
        
        for v in subviews {
            
            if v is UIControl && !(v is UIButton)
            {
                v.frame = CGRectOffset(rect, CGFloat (index) * w, 0)
                
                index++
                
               index = index == 2 ? 3 : index
                
            }
            // 设置中间按钮的frame
            middleButton.frame = CGRectOffset(rect, 2 * w, 0)
        }
    }
    
    // 懒加载中间的加号按钮
    lazy var middleButton: UIButton = {
        
        let btn = UIButton()
        
        btn.setImage((UIImage(named: "tabbar_compose_icon_add")), forState: UIControlState.Normal)
        btn.setImage((UIImage(named: "tabbar_compose_icon_add_highlighted")), forState: UIControlState.Highlighted)
        btn.setBackgroundImage((UIImage(named: "tabbar_compose_button")), forState: UIControlState.Normal)
        btn.setBackgroundImage((UIImage(named: "tabbar_compose_button_highlighted")), forState: UIControlState.Highlighted)
        
        // 因为是闭包中,要用self
        self.addSubview(btn)
        
        return btn
        }()
}
